<template>
  <el-dialog
    v-model="dialogVisible"
    title="规则配置"
    width="80%"
    :before-close="handleClose"
    class="rules-dialog"
  >
    <el-tabs v-model="activeTab" type="border-card">
      <el-tab-pane label="组件分类规则" name="component">
        <div class="rules-content">
          <div class="rules-header">
            <el-button type="primary" @click="addComponentCategory">
              <el-icon><Plus /></el-icon>
              添加组件分类
            </el-button>
          </div>
          
          <div class="rules-list">
            <el-card 
              v-for="(components, category) in componentRules" 
              :key="category"
              class="rule-card"
              shadow="hover"
            >
              <template #header>
                <div class="rule-header">
                  <span class="category-name">{{ category }}</span>
                  <el-button 
                    type="danger" 
                    size="small" 
                    @click="removeComponentCategory(category)"
                  >
                    <el-icon><Delete /></el-icon>
                  </el-button>
                </div>
              </template>
              
              <el-input
                v-model="componentRules[category]"
                type="textarea"
                :rows="3"
                placeholder="请输入组件列表，用逗号分隔"
                @change="updateComponentRule(category)"
              />
            </el-card>
          </div>
        </div>
      </el-tab-pane>
      
      <el-tab-pane label="错误分类规则" name="error">
        <div class="rules-content">
          <div class="rules-header">
            <el-button type="primary" @click="addErrorCategory">
              <el-icon><Plus /></el-icon>
              添加错误分类
            </el-button>
          </div>
          
          <div class="rules-list">
            <el-card 
              v-for="(patterns, category) in errorRules" 
              :key="category"
              class="rule-card"
              shadow="hover"
            >
              <template #header>
                <div class="rule-header">
                  <span class="category-name">{{ category }}</span>
                  <el-button 
                    type="danger" 
                    size="small" 
                    @click="removeErrorCategory(category)"
                  >
                    <el-icon><Delete /></el-icon>
                  </el-button>
                </div>
              </template>
              
              <el-input
                v-model="errorRules[category]"
                type="textarea"
                :rows="3"
                placeholder="请输入匹配模式，用换行分隔"
                @change="updateErrorRule(category)"
              />
            </el-card>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSave">保存</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import * as api from '@/api'

// Props
interface Props {
  modelValue: boolean
}

const props = defineProps<Props>()

// Emits
const emit = defineEmits<{
  'update:modelValue': [value: boolean]
}>()

// 状态
const activeTab = ref('component')
const componentRules = ref<Record<string, string>>({})
const errorRules = ref<Record<string, string>>({})

// 计算属性
const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 加载规则
const loadRules = async () => {
  try {
    const data = await api.getRules()
    
    // 转换组件规则
    componentRules.value = {}
    Object.entries((data as any).component_categories || {}).forEach(([category, components]: [string, any]) => {
      componentRules.value[category] = Array.isArray(components) ? components.join(', ') : components
    })
    
    // 转换错误规则
    errorRules.value = {}
    Object.entries((data as any).error_categories || {}).forEach(([category, patterns]: [string, any]) => {
      errorRules.value[category] = Array.isArray(patterns) ? patterns.join('\n') : patterns
    })
  } catch (error) {
    console.error('加载规则失败:', error)
    ElMessage.error('加载规则失败')
  }
}

// 添加组件分类
const addComponentCategory = async () => {
  try {
    const { value: categoryName } = await ElMessageBox.prompt('请输入新的组件分类名称:', '添加分类')
    if (!categoryName) return
    
    const { value: components } = await ElMessageBox.prompt('请输入组件列表（用逗号分隔）:', '组件列表')
    if (!components) return
    
    await api.addComponentCategory(categoryName, components.split(',').map(c => c.trim()))
    await loadRules()
    ElMessage.success('添加成功')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('添加失败')
    }
  }
}

// 删除组件分类
const removeComponentCategory = async (category: string) => {
  try {
    await ElMessageBox.confirm(`确定要删除分类 "${category}" 吗？`, '确认删除', {
      type: 'warning'
    })
    
    await api.removeComponentCategory(category)
    await loadRules()
    ElMessage.success('删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 更新组件规则
const updateComponentRule = async (category: string) => {
  try {
    const components = componentRules.value[category].split(',').map(c => c.trim())
    await api.updateRules({
      component_categories: {
        [category]: components
      }
    })
  } catch (error) {
    ElMessage.error('更新失败')
  }
}

// 添加错误分类
const addErrorCategory = async () => {
  try {
    const { value: categoryName } = await ElMessageBox.prompt('请输入新的错误分类名称:', '添加分类')
    if (!categoryName) return
    
    const { value: patterns } = await ElMessageBox.prompt('请输入匹配模式（用换行分隔）:', '匹配模式')
    if (!patterns) return
    
    await api.addErrorCategory(categoryName, patterns.split('\n').map(p => p.trim()))
    await loadRules()
    ElMessage.success('添加成功')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('添加失败')
    }
  }
}

// 删除错误分类
const removeErrorCategory = async (category: string) => {
  try {
    await ElMessageBox.confirm(`确定要删除分类 "${category}" 吗？`, '确认删除', {
      type: 'warning'
    })
    
    await api.removeErrorCategory(category)
    await loadRules()
    ElMessage.success('删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 更新错误规则
const updateErrorRule = async (category: string) => {
  try {
    const patterns = errorRules.value[category].split('\n').map(p => p.trim())
    await api.updateRules({
      error_categories: {
        [category]: patterns
      }
    })
  } catch (error) {
    ElMessage.error('更新失败')
  }
}

// 处理关闭
const handleClose = () => {
  dialogVisible.value = false
}

// 处理保存
const handleSave = () => {
  ElMessage.success('规则已保存')
  handleClose()
}

// 监听对话框显示
watch(dialogVisible, (visible) => {
  if (visible) {
    loadRules()
  }
})

onMounted(() => {
  if (dialogVisible.value) {
    loadRules()
  }
})
</script>

<style scoped>
.rules-dialog {
  max-width: 90vw;
}

.rules-content {
  padding: 20px 0;
}

.rules-header {
  margin-bottom: 20px;
}

.rules-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.rule-card {
  border-radius: 8px;
}

.rule-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.category-name {
  font-weight: 600;
  color: var(--color-text);
  text-transform: capitalize;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .rules-content {
    padding: 10px 0;
  }
  
  .rules-list {
    gap: 12px;
  }
  
  .rule-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
}

@media (max-width: 480px) {
  .rules-dialog {
    max-width: 95vw;
  }
  
  .category-name {
    font-size: 14px;
  }
}
</style> 